<template>
  <div class="container">
    <div class="search">
      <el-input placeholder="请输入账号查询" style="width: 200px" v-model="username"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="handleSearch">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="handleReset">重置</el-button>
    </div>
    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="handleBatchDelete">批量删除</el-button>
    </div>
    <div class="table">
      <el-table :data="tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="nickname" label="姓名"></el-table-column>
        <el-table-column prop="userphone" label="电话"></el-table-column>
        <el-table-column prop="idCard" label="身份证号"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column prop="useraddress" label="地址" width="120"></el-table-column>
        <el-table-column prop="userphoto" label="头像" width="120">
          <template #default="scope">
            <img :src="scope.row.userphoto" alt="头像" style="max-width: 100px; max-height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑抽屉 -->
    <el-drawer title="编辑管理员" v-model="editVisible" direction="rtl" size="40%" :destroy-on-close="true">
      <el-form :model="form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="账号">
          <el-input v-model="form.username" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.nickname" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.userphone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.idCard" placeholder="身份证号"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.useraddress" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="photo">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-drawer>

    <!-- 创建抽屉 -->
    <el-drawer title="创建管理员" v-model="addVisible" direction="rtl" size="40%" :destroy-on-close="true">
      <el-form :model="form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="账号">
          <el-input v-model="form.username" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.nickname" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.userphone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.idCard" placeholder="身份证号"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.useraddress" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="photo">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userListService, deleteUserService, findUserService, createUserService, updateUserService,batchDeleteUserService} from '@/api/user'

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const username = ref('')
const editVisible = ref(false)
const addVisible = ref(false)
const form = ref({})
const user = ref(JSON.parse(localStorage.getItem('xm-user') || '{}'))
const selectedRows = ref([])

const fetchData = async () => {
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      username: username.value
    }
    const response = await userListService(params)
    tableData.value = response.data.list
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

const handleSearch = async () => {
  try {
    const response = await findUserService(username.value)
    if (response.data) {
      tableData.value = [response.data]
      total.value = 1
    } else {
      ElMessage.warning('未找到用户')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('查询用户失败')
  }
}

const handleReset = () => {
  username.value = ''
  pageNum.value = 1
  fetchData()
}

const handleAdd = () => {
  form.value = {}
  addVisible.value = true
}

const handleEdit = (row) => {
  form.value = { ...row }
  editVisible.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      await batchDeleteUserService(ids)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  ElMessageBox.confirm('确定要删除选中的用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      for (const row of selectedRows.value) {
        await deleteUserService(row.id)
      }
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleSelectionChange = (val) => {
  selectedRows.value = val
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchData()
}

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage
  fetchData()
}

import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  form.value.userphoto = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg'&& rawFile.type !== 'image/png') {
    ElMessage.error('商品图片必须是JPG或PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('商品图片大小不能超过2MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  try {
    if (form.value.id) {
      await updateUserService(form.value)
      ElMessage.success('更新成功')
    } else {
      await createUserService(form.value)
      ElMessage.success('创建成功')
    }
    editVisible.value = false
    addVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('提交失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 30px;
}

.search {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.operation {
  margin-bottom: 20px;
}

.table {
  margin-bottom: 20px;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}

.el-button {
  margin: 0 5px;
}

.el-drawer {
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.el-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>